package com.ruoyi.qif.service.impl;

import java.time.YearMonth;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.qif.mapper.QifExpenditureMapper;
import com.ruoyi.qif.domain.QifExpenditure;
import com.ruoyi.qif.service.IQifExpenditureService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 锜风公寓-公账支出Service业务层处理
 *
 * @author David
 * @date 2025-11-03
 */
@Service
public class QifExpenditureServiceImpl implements IQifExpenditureService {

    private static final Logger log = LoggerFactory.getLogger(QifExpenditureServiceImpl.class);
    @Autowired
    private QifExpenditureMapper qifExpenditureMapper;

    /**
     * 查询锜风公寓-公账支出
     *
     * @param expenditureId 锜风公寓-公账支出主键
     * @return 锜风公寓-公账支出
     */
    @Override
    public QifExpenditure selectQifExpenditureByExpenditureId(Long expenditureId) {
        return qifExpenditureMapper.selectQifExpenditureByExpenditureId(expenditureId);
    }

    /**
     * 查询锜风公寓-公账支出列表
     *
     * @param qifExpenditure 锜风公寓-公账支出
     * @return 锜风公寓-公账支出
     */
    @Override
    public List<QifExpenditure> selectQifExpenditureList(QifExpenditure qifExpenditure) {
        // 初始化参数Map（若依推荐用params存储额外条件）
        if (qifExpenditure.getParams() == null) {
            qifExpenditure.setParams(new HashMap<>(2));
        }

        // 获取当前年月（默认查询条件）
        Calendar cal = Calendar.getInstance();
        int year = qifExpenditure.getQueryYear() != null ? qifExpenditure.getQueryYear() : cal.get(Calendar.YEAR);
        int month = qifExpenditure.getQueryMonth() != null ? qifExpenditure.getQueryMonth() : (cal.get(Calendar.MONTH) + 1); // 月份+1（Calendar月份从0开始）

        // 2. 生成字符串格式的起止日期（yyyy-MM-dd）
        String startDateStr = String.format("%d-%02d-01", year, month); // 当月1日（如2025-10-01）
        // 计算当月最后一天（处理2月、大月小月）
        YearMonth yearMonth = YearMonth.of(year, month);
        int lastDay = yearMonth.lengthOfMonth();
        String endDateStr = String.format("%d-%02d-%02d", year, month, lastDay); // 当月最后一天（如2025-10-31）

        // 3. 存入params（字符串类型）
        qifExpenditure.getParams().put("expenditureDateStart", startDateStr);
        qifExpenditure.getParams().put("expenditureDateEnd", endDateStr);
        return qifExpenditureMapper.selectQifExpenditureList(qifExpenditure);
    }

    /**
     * 新增锜风公寓-公账支出
     *
     * @param qifExpenditure 锜风公寓-公账支出
     * @return 结果
     */
    @Override
    public int insertQifExpenditure(QifExpenditure qifExpenditure) {
        qifExpenditure.setCreateTime(DateUtils.getNowDate());
        return qifExpenditureMapper.insertQifExpenditure(qifExpenditure);
    }

    /**
     * 修改锜风公寓-公账支出
     *
     * @param qifExpenditure 锜风公寓-公账支出
     * @return 结果
     */
    @Override
    public int updateQifExpenditure(QifExpenditure qifExpenditure) {
        qifExpenditure.setUpdateTime(DateUtils.getNowDate());
        return qifExpenditureMapper.updateQifExpenditure(qifExpenditure);
    }

    /**
     * 批量删除锜风公寓-公账支出
     *
     * @param expenditureIds 需要删除的锜风公寓-公账支出主键
     * @return 结果
     */
    @Override
    public int deleteQifExpenditureByExpenditureIds(String expenditureIds) {
        return qifExpenditureMapper.deleteQifExpenditureByExpenditureIds(Convert.toStrArray(expenditureIds));
    }

    /**
     * 删除锜风公寓-公账支出信息
     *
     * @param expenditureId 锜风公寓-公账支出主键
     * @return 结果
     */
    @Override
    public int deleteQifExpenditureByExpenditureId(Long expenditureId) {
        return qifExpenditureMapper.deleteQifExpenditureByExpenditureId(expenditureId);
    }


    @Override
    @Transactional
    public String importQifExpenditure(List<QifExpenditure> qifExpenditureList, boolean updateSupport) {
        if (StringUtils.isNull(qifExpenditureList) || qifExpenditureList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        for (QifExpenditure qifExpenditure : qifExpenditureList) {
            try {
                // 修改查询已存在数据的方法调用
                QifExpenditure existingExpenditure = qifExpenditureMapper.selectQifExpenditureByDateAndDescription(
                        qifExpenditure.getExpenditureDate(), qifExpenditure.getRemark());
                if (StringUtils.isNull(existingExpenditure)) {
                    qifExpenditure.setCreateBy(operName);
                    qifExpenditure.setCreateTime(DateUtils.getNowDate());
                    qifExpenditureMapper.insertQifExpenditure(qifExpenditure);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、导入成功");
                } else if (updateSupport) {
                    qifExpenditure.setUpdateBy(operName);
                    qifExpenditure.setUpdateTime(DateUtils.getNowDate());
                    qifExpenditureMapper.updateQifExpenditure(qifExpenditure);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、数据已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很遗憾，导入失败 " + failureNum + " 条数据：");
            throw new RuntimeException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条。");
        }
        return successMsg.toString();

    }
}
